package com.xnyzc.lhy.resource.util.worksheet;


import com.qcloud.cos.utils.Md5Utils;
import com.xnyzc.lhy.common.util.MD5Util;
import com.xnyzc.lhy.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 合力服务签名工具类
 */
@Slf4j
public class HeliSignUtil {
    private static String CC_App_Id = "10001";
    private static String CC_App_Secret = "ba9e69e9ffd2417eb46b369f323f002c";

    /**
     * 创建签名
     * @param
     * @return
     */
    public static<T> String createSig(T t){
        Map<String, String> requestParams = new HashMap<>(16);
        try {
            requestParams = BeanUtils.describe(t);
            requestParams.remove("class");
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        if(requestParams == null){
            requestParams = new HashMap<>(16);
        }
        requestParams.put("app_id", CC_App_Id);
        StringBuilder paramsBuffer = new StringBuilder("");
        Object[] keys = requestParams.keySet().toArray();
        Arrays.sort(keys);

        for (Object key : keys) {
            String value = requestParams.get(key);
            if (!"".equals(StringUtil.isNullReturnEmpty((value)))) {
                paramsBuffer.append(key + "=" + value + "&");
            }
        }

        String params = "";
        if (paramsBuffer.length() > 0) {
            params += paramsBuffer.substring(0, paramsBuffer.length() - 1);
        }
        String signStr=params + CC_App_Secret;
        try {
            signStr = URLEncoder.encode(signStr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String sig = EncryptTool.getInstance().md5(signStr);
        return sig;
    }
}
